<template>
  <div class="innerPageTable-box-OneTwo searchAdapt-assignPosition assignPosition">
    <Form :model="employeeInfo" label-position="top" class="ivu-form-no-margin-bottom" inline>
      <template>
        <Row :gutter="16">
          <Col span="6">
            <!-- 部门编码 -->
            <Form-item prop="code" :label="$t('module.orgManage.jobCode')">
              <Input
                type="text"
                
                v-model.trim="employeeInfo.positionCode"
                :maxlength="30"
                disabled
              ></Input>
            </Form-item>
          </Col>
          <Col span="6">
            <!-- 部门名称 -->
            <Form-item prop="name" :label="$t('module.orgManage.jobName')">
              <Input
                type="text"
                
                v-model.trim="employeeInfo.positionName"
                :maxlength="30"
                disabled
              ></Input>
            </Form-item>
          </Col>
        </Row>
      </template>
    </Form>

    <Row :gutter="16" type="flex" justify="center" align="middle" class="table-border-top">
      <Col span="10" class="table-border">
        <div class="left-content">
          <!-- 搜索区域 -->
          <SelfAdaption>
            <Form :model="searchFormOne" slot="adaption-bar" label-position="top" inline>
              <Input
                suffix="ios-search"
                type="text"
                v-model.trim="searchFormOne.nameOrNo"
                :placeholder="$t('module.orgManage.searchEmployee')"
                @input="searchNotEmployee"
              />
              <Input type="text" class="form-control" style="display:none" />
            </Form>
          </SelfAdaption>
          <InnerPageTable ref="tableOne" :config="pageTableConfig" :key="refrushOne"></InnerPageTable>
        </div>
      </Col>
      <Col span="4">
        <div class="transfer-center tansDiv">
          <div>
            <div class="addUserBtn" @click="addEmp">
              {{$t('module.orgManage.addEmployee')}}
              <span>&gt;&gt;</span>
            </div>
            <div class="deleUserBtn" @click="deleteEmp">
              <span>&lt;&lt;</span>
              {{$t('module.orgManage.removeEmployee')}}
            </div>
          </div>
        </div>
      </Col>
      <Col span="10" class="table-border">
        <div class="right-content">
          <!-- 搜索区域 -->
          <SelfAdaption>
            <Form :model="searchFormTwo" slot="adaption-bar" label-position="top" inline>
              <Input
                suffix="ios-search"
                v-model="searchFormTwo.nameOrNo"
                :placeholder="$t('module.orgManage.searchEmployee')"
                @input="searchYesEmployee"
              />
              <Input type="text" class="form-control" style="display:none" />
            </Form>
          </SelfAdaption>
          <InnerPageTable ref="tableTwo" :config="pageTableConfigTwo" :key="refrushTwo"></InnerPageTable>
        </div>
      </Col>
    </Row>
  </div>
</template>
<script>
import { getNotAssign, getAssign, deleteEmp, addEmp, change, forceChange } from "@/api/orgApi.js";
import locales from "../locales.js";
import { getDepartmentTemplateList, templateDetail } from "@/api/extendAttrApi.js";

export default {
  mixins: [locales],
  // components: {},
  props: {
    departmentForm: {
      type: Object,
      default() {
        return {};
      }
    },
    positionInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    employeeInfo: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      refrushOne: 1,
      refrushTwo: 1,
      fun: null,
      searchFormOne: {
        status: 0, //0为在职，1为离职。（只要显示在职员工）
        nameOrNo: "",
        positionCode: "",
        orgId: ""
      },
      searchFormTwo: {
        nameOrNo: "",
        positionCode: "",
        orgId: ""
      },
      selectedOne: "",
      selectedTwo: "",
      pageTableConfig: {},
      pageTableConfigTwo: {}
    };
  },
  created() {
    let _this = this;
    this.pageTableConfig = {
      onSelectionChange(_selected) {
        _this.selectedOne = _selected;
      },
      hasSelectionArea: false,
      loadDataFn: this.getNotAssign,
      columnsFn: this.columnsOne,
      autoFirst: false,
      selectionAreaItem: { key: "employeeNo", title: "name" }
    };
    this.pageTableConfigTwo = {
      onSelectionChange(_selected) {
        _this.selectedTwo = _selected;
      },
      hasSelectionArea: false,
      loadDataFn: this.getAssign,
      columnsFn: this.columnsTwo,
      autoFirst: false,
      selectionAreaItem: { key: "employeeNo", title: "employeeName" },
      rowClassNameFn: this.rowClassName // 自定义行样式
    };
  },
  mounted: function() {
    this.init();
  },
  methods: {
    // 自定义行样式
    rowClassName(row) {
      if (row.employeeStatus == 1) {
        return "tableDisableStyle";
      }
    },
    //   防抖函数
    debounce: function(fn, wait = 1000) {
      if (this.fun !== null) {
        clearTimeout(this.fun);
      }
      this.fun = setTimeout(fn, wait);
    },
    init() {
      this.searchFormTwo.positionCode = this.employeeInfo.positionCode;
      this.searchFormTwo.orgId = this.employeeInfo.orgId;

      this.searchFormOne.positionCode = this.employeeInfo.positionCode;
      this.searchFormOne.orgId = this.employeeInfo.orgId;
      this.$refs["tableOne"].load(this.searchFormOne, 1);
      this.$refs["tableTwo"].load(this.searchFormTwo, 1);
    },
    // 搜索 已分配的员工(初始化：mounted中调用)
    searchYesEmployee() {
      this.searchFormTwo.positionCode = this.employeeInfo.positionCode;
      this.searchFormTwo.orgId = this.employeeInfo.orgId;

      this.debounce(this.handleSearchYesEmployee, 300);
    },
    handleSearchYesEmployee() {
      this.$refs["tableTwo"].load(this.searchFormTwo, 1);
    },
    // 搜索 未分配的员工(初始化：mounted中调用)
    searchNotEmployee() {
      this.searchFormOne.positionCode = this.employeeInfo.positionCode;
      this.searchFormOne.orgId = this.employeeInfo.orgId;

      this.debounce(this.handleSearchNotEmployee, 300);
    },
    handleSearchNotEmployee() {
      this.$refs["tableOne"].load(this.searchFormOne, 1);
    },
    // 选中未分配的数据 分配职位
    getNotSelected() {
      let arr = [];
      for (let item of this.selectedOne || []) {
        arr.push(item.employeeNo);
      }
      return arr;
    },
    // 点击加号 分配职位
    addSingle(code) {
      let arr = [];
      arr.push(code);
      let param = {
        empList: arr,
        jobCode: this.positionInfo.jobCode,
        jobCodeDesc: this.positionInfo.jobName,
        positionDesc: this.positionInfo.name,
        positionCode: this.positionInfo.code,
        departmentDesc: this.departmentForm.name,
        departmentCode:this.departmentForm.code,
        orgId: this.employeeInfo.orgId
      };
      addEmp(param)
        .then(data => {
          this.init();
          this.$message.success({
            content: this.$t("module.orgManage.isAssign")
          });
        })
        .catch(data => {});
    },
    addEemployee(code) {
      this.debounce(() => {
        this.addSingle(code);
      }, 500);
    },

    //批量添加
    addBatch() {
      let receiptSeqIds = this.getNotSelected();
      if (receiptSeqIds.length == 0) {
        this.$message.error({
          content: this.$t("common.warning.selctAddElement"),
          duration: 3
        });
      } else {
        let param = {
          empList: receiptSeqIds,
          jobCode: this.positionInfo.jobCode,
          jobCodeDesc: this.positionInfo.jobName,
          positionDesc: this.positionInfo.name,
          positionCode: this.positionInfo.code,
          departmentDesc: this.departmentForm.name,
          departmentCode:this.departmentForm.code,
          orgId: this.employeeInfo.orgId
        };
        addEmp(param)
          .then(data => {
            ++this.refrushOne;
            ++this.refrushTwo;
            this.$nextTick(() => {
              this.init();
              this.selectedOne = [];
              this.$message.success({
                content: this.$t("module.orgManage.isAssign")
              });
            });
          })
          .catch(data => {});
      }
    },
    addEmp() {
      this.debounce(this.addBatch, 500);
    },

    // 点击删除图标 移除职位
    deleteEemployee(code) {
      new $confirm(this.$t("common.warning.confirmToRemove"), this).then(() => {
        let arr = [];
        arr.push(code);
        let param = {
          orgId: this.employeeInfo.orgId,
          positionCode: this.employeeInfo.positionCode,
          empList: arr
        };
        deleteEmp(param)
          .then(data => {
            this.init();
            this.$message.success({
              content: this.$t("module.orgManage.isRemove")
            });
          })
          .catch(data => {});
      });
    },
    // 选中已分配的数据 移除职位
    getSelected() {
      let arr = [];
      for (let ff of this.selectedTwo || []) {
        arr.push(ff.employeeNo);
      }
      return arr;
    },
    deleteEmp() {
      let receiptSeqIds = this.getSelected();
      if (receiptSeqIds.length == 0) {
        this.$message.error({
          content: this.$t("common.warning.selctAddElement"),
          duration: 3
        });
      } else {
        let param = {
          orgId: this.employeeInfo.orgId,
          positionCode: this.employeeInfo.positionCode,
          empList: receiptSeqIds
        };
        deleteEmp(param)
          .then(data => {
            ++this.refrushOne;
            ++this.refrushTwo;
            this.$nextTick(() => {
              this.init();
              this.selectedTwo = [];
              this.$message.success({
                content: this.$t("module.orgManage.isRemove")
              });
            });
          })
          .catch(data => {});
      }
    },
    // 获取已分配的人员
    getAssign({ responseProcess, param }) {
      getAssign(param).then(data => {
        responseProcess(data);
      });
    },
    // 获取未分配的人员
    getNotAssign({ responseProcess, param }) {
      getNotAssign(param).then(data => {
        responseProcess(data);
      });
    },
    columnsOne() {
      return [
        {
          type: "selection",
          align: "center"
        },
        {
          title: this.$t("module.orgManage.employeeName"),
          key: "name"
        },
        {
          title: this.$t("module.orgManage.employeeNum"),
          key: "employeeNo"
        },
        {
          title: this.$t("module.orgManage.operation"),
          align: "center",
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: [
                  {
                    type: "icon",
                    icon: "md-add",
                    text: this.$t("common.add"),
                    handle: () => {
                      this.addEemployee(params.row.employeeNo);
                    }
                  }
                ]
              }
            });
          }
        }
      ];
    },
    columnsTwo() {
      return [
        {
          type: "selection",
          align: "center"
        },
        {
          title: this.$t("module.orgManage.employeeName"),
          key: "employeeName"
        },
        {
          title: this.$t("module.orgManage.employeeNum"),
          key: "employeeNo"
        },
        {
          title: this.$t("module.orgManage.mainOrPart"),
          key: "enabled",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: params.row.mainPostFlag == "Y" ? "warning" : "info",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.selsect(params.row.id);
                    }
                  }
                },
                params.row.mainPostFlag == "Y"
                  ? this.$t("module.orgManage.mainOccupation")
                  : this.$t("module.orgManage.pluralism")
              )
            ]);
          }
        },
        {
          title: this.$t("module.orgManage.operation"),
          align: "center",
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: [
                  {
                    type: "icon",
                    icon: "ios-trash-outline",
                    text: this.$t("common.remove"),
                    handle: () => {
                      this.deleteEemployee(params.row.employeeNo);
                    }
                  }
                ]
              }
            });
          }
        }
      ];
    },
    // 主兼职切换
    selsect(id) {
      let param = {
        id: id,
        employeeNo: "",
        mainPostFlag: ""
      };
      let data = this.$refs["tableTwo"].getTableData();
      for (let i = 0; i < data.length; i++) {
        if (data[i].id == id) {
          param.employeeNo = data[i].employeeNo;
          if (data[i].mainPostFlag == "Y") {
            param.mainPostFlag = "N";
          } else if (data[i].mainPostFlag == "N") {
            param.mainPostFlag = "Y";
          }
        }
      }

      change(param)
        .then(response => {
          let result = response.data;
          if (result.changMainPostStatus == false) {
            new $confirm(
              `确认继续操作？员工主职由"${result.originMainPost}"更新为"${result.changedMainPost}",原主职更新为兼职`,
              this
            ).then(() => {
              forceChange(param).then(data => {
                this.searchYesEmployee();
                this.$message.success({
                  content: this.$t("module.orgManage.selectSuccess")
                });
              });
            });
          } else {
            this.searchYesEmployee();
            this.$message.success({
              content: this.$t("module.orgManage.selectSuccess")
            });
          }
        })
        .catch(data => {});
    }
  },
  watch: {}
};
</script>
<style lang="less">
.searchAdapt-assignPosition {
  .ivu-input-wrapper {
    .ivu-input-suffix {
      top: 0;
    }
  }
  .table-border-top {
    margin-top: 30px;
    .transfer-center {
      display: flex;
      justify-content: center;
      .addUserBtn {
        margin-bottom: 20px;
        background: #ff6f4b;
        color: white;
      }
      .deleUserBtn {
        color: #ff6f4b;
        border: 1px solid #ff6f4b;
      }
      .addUserBtn,
      .deleUserBtn {
        width: 120px;
        min-height: 25px;
        line-height: 25px;
        padding: 0 10px;
        text-align: center;
        cursor: pointer;
        user-select: none;
      }
    }
    .table-border {
      .inner-table {
        // border: 1px solid #eee;
        .search-bar,
        .table-bar {
          display: none;
        }
        .single-table-con {
          padding-top: 0;
          padding-bottom: 5px;
        }
      }
      .left-content,
      .right-content {
        border: 1px solid #eee;
      }
      .self-adaption-wrap {
        padding: 10px 5px 0;
      }
    }
    .search-input-margin-bottom {
      margin-bottom: -40px;
      margin-top: 20px;
    }
    .buttonPositon {
      text-align: center;
    }
    .single-table-con {
      .ivu-table-wrapper {
        min-height: 360px !important;
        max-height: 400px !important;
        .ivu-table {
          .ivu-table-body {
            max-height: auto !important;
          }
        }
      }
    }
  }
}
// .rp-confirm {
//     .ivu-modal {
//         width: 496px !important;
//     }
//     .rp-confirm-content {
//         width: 100%;
//         text-align: center !important;
//         img {
//         width: 90px;
//         height: 90px;
//         }
//         p {
//         font-size: 16px;
//         color: #333;
//         text-align: left !important;
//         }
//     }
// }
</style>
